<?php namespace Poscms;
/**
 * POSCMS框架文件
 * 二次开发时请勿修改本文件
 * 四川迅睿云软件开发有限公司 www.xunruicms.com
 */
class Module extends \Poscms\Common {

    /**
     * 构造函数
     */
    public function __construct() {
        parent::__construct();
        $this->_module_init(APP_DIR);
    }

    /**
     * 模块内容/扩展购买页
     */
    protected function _show_buy() {

        $id = (int)$this->input->get('id');
        $eid = (int)$this->input->get('eid');

        $mod = $this->get_cache('module-'.SITE_ID.'-'.$this->dir);
        !$mod && exit(dr_safe_replace($this->input->get('callback', TRUE)).'('.json_encode(array('html' => '模块【'.$this->dir.'】不存在')).')');

        $name = $id ? 'show'.$this->dir.SITE_ID.$id : 'extend'.$this->dir.SITE_ID.$id;
        $data = $this->get_cache_data($name);

        if ($id) {
            // 模块内容
            if (!$data) {
                $data = \Poscms\Service::M('content', $this->dir)->get($id);
                !$data && exit(dr_safe_replace($this->input->get('callback', TRUE)).'('.json_encode(array('html' => '内容不存在')).')');
            }
            // 字段
            $cat = $mod['category'][$data['catid']];
            // 格式化输出自定义字段
            $fields = $mod['field'];
            $fields = $cat['field'] ? array_merge($fields, $cat['field']) : $fields;
            $table = SITE_ID.'_'.$this->dir.'_buy';
            $where = 'cid='.$id.' and uid='.$this->uid;
            //
            $tpl = 'show_buy.html';
        } elseif ($eid) {
            // 模块内容扩展
            if (!$data) {
                $data = \Poscms\Service::M('content', $this->dir)->get_extend($eid);
                !$data && exit(dr_safe_replace($this->input->get('callback', TRUE)).'('.json_encode(array('html' => '扩展内容不存在')).')');
            }
            // 格式化输出自定义字段
            $fields = $mod['extend'];
            $table = SITE_ID.'_'.$this->dir.'_extend_buy';
            $where = 'eid='.$eid.' and uid='.$this->uid;
            //
            $tpl = 'extend_buy.html';
        } else {
            echo dr_safe_replace($this->input->get('callback', TRUE)).'('.json_encode(array('html' => '无参数')).')';exit;
        }

        $fields['inputtime'] = array('fieldtype' => 'Date');
        $fields['updatetime'] = array('fieldtype' => 'Date');

        $data = $this->field_format_value($fields, $data, 0);

        // 查找收费有收费字段
        $fees = '';
        foreach ($fields as $t) {
            if ($t['fieldtype'] == 'Fees') {
                $fees = $t['fieldname'];
                if ($t['setting']['option']['mode']) {
                    // 按会员组模式
                    $this->markrule = $this->member['groupid'];
                }
                break;
            }
        }

        // 无收费字段
        if (!$fees) {
            echo dr_safe_replace($this->input->get('callback', TRUE)).'('.json_encode(array('html' => '此模块内容没有收费字段')).')';exit;
        } elseif (!isset($data[$fees])) {
            echo dr_safe_replace($this->input->get('callback', TRUE)).'('.json_encode(array('html' => '此模块内容收费字段内容没有填写')).')';exit;
        }

        // 判断是否开启阅读收费
        $value = $data[$fees];
        if (is_numeric($value)) {
            $score = abs(intval($value));
        } else {
            $score = abs((int)$value[$this->markrule]);
        }

        if ($value) {
            /*
            if (!$this->markrule || strlen($this->markrule) == 1) {
                #exit(dr_safe_replace($this->input->get('callback', TRUE)).'('.json_encode(array('html' => '当前会员组（'.($this->member['groupname'] ? $this->member['groupname'] : '游客').'）无权限查看收费内容')).')');
            }*/
            // 判断用户权限
            if ($this->uid) {
                $is_buy = $this->db->where($where)->count_all_results($table);
                $data['score'] = $score;
                $data['is_buy'] = $data['score'] ? $is_buy : 1;
                // 当前类型是扩展时判定一下主内容是否被购买
                $eid && $data['is_buy'] == 0 && $data['is_buy'] = $this->db->where('cid='.(int)$data['cid'].' and eid=0 and uid='.$this->uid)->count_all_results($table);
            } else {
                exit(dr_safe_replace($this->input->get('callback', TRUE)).'('.json_encode(array('html' => '收费内容请登录之后再查看')).')');
            }
        } else {
            // 未开启时默认为显示
            $data['is_buy'] = 1;
        }

        if (!$data['is_buy']
            && $this->input->get('action') == 'confirm') {
            // 会员未登录
            !$this->member && $this->_goto_member_login();
            // 虚拟币检查
            -$data['score'] + $this->member['score'] < 0 && $this->msg(fc_lang(SITE_SCORE.'不足！本次需要%s'.SITE_SCORE.'，当前余额%s'.SITE_SCORE, $data['score'], $this->member['score']));
            // 扣减虚拟币
            \Poscms\Service::M('member')->update_score(1, $this->uid, -$data['score'], '', '购买《'.($data['name'] ? $data['name'] : $data['title']).'》');
            // 卖家增加
            $data['uid'] && \Poscms\Service::M('member')->update_score(1, $data['uid'], $data['score'], '', '卖出《'.($data['name'] ? $data['name'] : $data['title']).'》');
            // 记录购买历史
            $insert = array(
                'uid' => $this->uid,
                'url' => $data['url'],
                'score' => $data['score'],
                'thumb' => $data['preview'] ? $data['preview'] : ($data['thumb'] ? $data['thumb'] : ''),
                'inputtime' => SYS_TIME
            );
            if ($id) {
                $insert['cid'] = $id;
                $insert['title'] = $data['title'];
            } else {
                $insert['eid'] = $eid;
                $insert['cid'] = $data['cid'];
                $insert['title'] = ($data['ctitle'] ? $data['ctitle'].' - ' : '').$data['name'];
            }
            $this->db->insert($table, $insert);
            $this->msg(fc_lang('购买成功'), $data['url'], 1);
        } else {
            $this->template->assign($data);
            ob_start();
            $this->template->display($tpl);
            $html = ob_get_contents();
            ob_clean();
            echo dr_safe_replace($this->input->get('callback', TRUE)).'('.json_encode(array('html' => $html)).')';exit;
        }
    }


    // 会员中心获取可用字段
    protected function _get_member_field($catid) {

        // 主字段
        $field = $this->get_cache('module-'.SITE_ID.'-'.MOD_DIR, 'field');
        // 指定栏目字段
        $category = $this->get_cache('module-'.SITE_ID.'-'.APP_DIR, 'category', $catid, 'field');
        if ($category) {
            $tmp = $field;
            $field = array();
            if (isset($tmp['title'])) {
                $field['title'] = $tmp['title'];
                unset($tmp['title']);
                $field = array_merge($field, $category, $tmp);
            } else {
                $field = array_merge($category, $tmp);
            }
        }

        // 判断是否审核，若审核的话就不需要显示状态字段
        if (!$this->uid) {
            return $field;
        }

        $field['status'] = array(
            'name' => fc_lang('状态'),
            'ismain' => 1,
            'ismember' => 1,
            'fieldname' => 'status',
            'fieldtype' => 'Radio',
            'setting' => array(
                'option' => array(
                    'value' => 9,
                    'options' => fc_lang('正常').'|9'.chr(13).fc_lang('关闭').'|10'
                ),
                'validate' => array(
                    'tips' => fc_lang('关闭状态起内容暂存作用，除自己和管理员以外的人均无法访问'),
                )
            )
        );

        return $field;
    }

    /**
     * 栏目权限验证
     *
     * @param	intval	$catid	栏目id
     * @param	string	$option	权限选项
     * @return	bool
     */
    public function is_category_auth($catid, $option) {

        if ($this->admin['adminid'] == 1 || !$catid || !$option) {
            return TRUE;
        }

        return $this->get_cache('module-'.SITE_ID.'-'.$this->dir, 'category', $catid, 'setting', 'admin', $this->admin['adminid'], $option);
    }

    /**
     * 栏目选择
     *
     * @param array			$data		栏目数据
     * @param intval/array	$id			被选中的ID，多选是可以是数组
     * @param string		$str		属性
     * @param string		$default	默认选项
     * @param intval		$onlysub	只可选择子栏目
     * @param intval		$is_push	是否验证权限
     * @param intval		$is_first	是否返回第一个可用栏目id
     * @return string
     */
    public function select_category($data, $id = 0, $str = '', $default = ' -- ', $onlysub = 0, $is_push = 0, $is_first = 0) {

        $cache = md5(dr_array2string($data).dr_array2string($id).$str.$default.$onlysub.$is_push.$is_first.$this->member['uid']);
        if ($cache_data = $this->get_cache_data($cache)) {
            return $cache_data;
        }

        $tree = array();
        $first = 0; // 第一个可用栏目
        $string = '<select class=\'form-control\' '.$str.'>';

        $default && $string.= "<option value='0'>$default</option>";

        if (is_array($data)) {
            foreach($data as $t) {
                // 外部链接不显示
                $is_link = isset($t['setting']['linkurl']) && $t['setting']['linkurl'] ? 1 : (isset($t['tid']) && $t['tid'] == 2 ? 1 : 0);
                if ($is_link) {
                    continue;
                }
                // 单页且为最终单页不显示
                if (isset($t['tid']) && $t['tid'] == 0 && !$t['child']) {
                    continue;
                }
                $t['html_disabled'] = 0;
                // 验证权限
                if ($t['pcatpost']) {
                    // 父栏目可发布时的权限
                    if ($is_push) {
                        if (IS_MEMBER && isset($this->module_rule[$t['id']]) && !$this->module_rule[$t['id']]['add']) {
                            // 会员中心用户发布权限
                            continue;
                        } elseif (IS_ADMIN && !$this->is_category_auth($t['id'], 'add') && !$this->is_category_auth($t['id'], 'edit')) {
                            // 后台角色发布和修改权限
                            continue;
                        } elseif (isset($t['tid']) && $t['tid'] == 0 && $t['child']) {
                            // 如果父栏目是单页，且勾选了fu栏目可发布时，就禁用单页
                            $t['html_disabled'] = $onlysub ? 1 : 0;
                        } elseif ($t['mid'] != $this->dir) {
                            continue;
                        }
                    } else {
                        // 是否可选子栏目
                        $t['html_disabled'] = $onlysub ? 1 : 0;
                    }
                    // 选中操作
                    $t['selected'] = '';
                    if (is_array($id)) {
                        $t['selected'] = in_array($t['id'], $id) ? 'selected' : '';
                    } elseif(is_numeric($id)) {
                        $t['selected'] = $id == $t['id'] ? 'selected' : '';
                    }
                } else {
                    // 正常栏目权限
                    if ($is_push && $t['child'] == 0) {
                        if (IS_MEMBER && !$this->module_rule[$t['id']]['add']) {
                            continue;
                        } elseif (IS_ADMIN && !$this->is_category_auth($t['id'], 'add') && !$this->is_category_auth($t['id'], 'edit')) {
                            continue;
                        } elseif ($t['mid'] && $t['mid'] != $this->dir) {
                            continue;
                        }
                    }
                    // 选中操作
                    $t['selected'] = '';
                    if (is_array($id)) {
                        $t['selected'] = in_array($t['id'], $id) ? 'selected' : '';
                    } elseif(is_numeric($id)) {
                        $t['selected'] = $id == $t['id'] ? 'selected' : '';
                    }
                    // 是否可选子栏目
                    $t['html_disabled'] = $onlysub && $t['child'] != 0 ? 1 : 0;
                }
                // 第一个可用子栏目
                $first == 0 && $t['child'] == 0 && $first = $t['id'];
                if (isset($t['permission'])) {
                    unset($t['permission']);
                }
                if (isset($t['setting'])) {
                    unset($t['setting']);
                }
                $tree[$t['id']] = $t;
            }
        }

        if (IS_ADMIN && $this->admin['adminid'] > 1 && !$tree && $data) {
            if ($this->router->method == 'add') {
                $string = '<label style="padding-top:8px"><font color="red">你没有对此角色设置可用的管理栏目，在栏目管理中对具体的栏目进行设置管理权限</font></label>';
            } else {
                $string = '<label><font color="red">无栏目内容管理权限</font></label>';
            }

        } else {
            $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
            $str2 = "<optgroup label='\$spacer \$name'></optgroup>";

            \Poscms\Service::L('dtree');
            $this->dtree->init($tree);

            $string.= $this->dtree->get_tree_category(0, $str, $str2);
            $string.= '</select>';

            if ($is_first) {
                $mark = "value='";
                $first2 = (int)substr($string, strpos($string, $mark) + strlen($mark));
                $first = $first2 ? $first2 : $first;
            }
        }


        $data = $is_first ? array($string, $first) : $string;
        $tree && $this->set_cache_data($cache, $data, 7200);

        return $data;
    }

    /**
     * 通过之后的审核状态值
     *
     * @param	intval	$uid	会员uid
     * @param	intval	$catid	栏目id
     * @param	intval	$status	原状态
     * @return	intval	新状态
     */
    protected function _get_verify_status($uid, $catid, $status) {

        $member = \Poscms\Service::M('member')->get_base_member($uid);
        $verify = $this->get_cache('module-'.SITE_ID.'-'.$this->dir, 'category', $catid, 'permission', $member['markrule'], 'verify');
        if (!$verify) {
            return 9;
        }

        $data = $this->get_cache('verify');

        return !$data[$verify] || dr_count($data[$verify]['verify']) <= $status ? 9 : $status + 1;
    }

    /**
     * 会员中心初始化
     */
    protected function _init_member($module) {

        \Poscms\Service::L('Dfield', array($this->dir));
        $this->field = $this->module['field'];

        // 当前会员组可用的推荐位
        $data = $module['setting']['flag'];
        if ($data) {
            foreach ($data as $i => $t) {
                isset($t[$this->member['mark']])
                && $t[$this->member['mark']]
                && $t['name'] && $this->flag[$i] = $t;
            }
        }

    }
}